<?php
namespace app\admin\controller;
use think\facade\Db;
use think\facade\Request;
use think\facade\Env;

class UpFiles extends Base
{
	// 上传规则
	protected $fileValidate;
	protected $imageValidate;

	public function initialize()
    {
    	$config = Db::name('config')->where('group','=','uploads')->select();
        $currentData = array();
        foreach ($config as $key => $value) {
            $currentData[$value['name']] = $value['value'];
        }

        $filemax = $currentData['file_size'];
        $file_img_ext = $currentData['file_pic_ext'];
        $file_file_ext = $currentData['file_file_ext'];

        $this->imageValidate = [
        	'image' => 'filesize'.$filemax.'|'.$file_img_ext,
        ];
        $this->fileValidate = [
        	'file' => 'filesize'.$filemax.'|'.$file_file_ext,
        ];
        parent::initialize(); 
    }

    // 图片文件上传
	public function image(){
		$config = Db::name('config')->where('group','=','uploads')->select();
        $currentData = array();
        foreach ($config as $key => $value) {
            $currentData[$value['name']] = $value['value'];
        }
        // 获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件
        $fileObj = request()->file($fileKey[0]);
        $file = [];
        foreach ($fileObj as $key => $value) {
            $file[$key] = $value;
        }
        $result = [];
        try {
	        validate($this->imageValidate)->check($file);
	        $savename = \think\facade\Filesystem::disk('public')->putFile('images', $fileObj);
	        $result['code'] = 1;
	        $result['info'] = '图片上传成功!';
	        $result['filename'] = $fileObj->getOriginalName();
	        $path=str_replace('\\','/',$savename);
	        $result['url'] = '/storage/'.$path;

	    } catch (\think\exception\ValidateException $e) {
	    	$result['code'] =0;
            $result['info'] =  $e->getMessage();
            $result['url'] = '';
	    }

	    return $result;
    }
    // edit uploads
    // 富文本编辑器
    public function edit_image(){
		$config = Db::name('config')->where('group','=','uploads')->select();
        $currentData = array();
        foreach ($config as $key => $value) {
            $currentData[$value['name']] = $value['value'];
        }
        // 获取上传文件表单字段名
        $fileKey = array_keys(request()->file());
        // 获取表单上传文件
        $fileObj = request()->file($fileKey[0]);
        $file = [];
        foreach ($fileObj as $key => $value) {
            $file[$key] = $value;
        }
        $result = [];
        try {
	        validate($this->imageValidate)->check($file);
	        $savename = \think\facade\Filesystem::disk('public')->putFile('images', $fileObj);
	        $result['code'] = 0;
	        $result['msg'] = '图片上传成功!';
	        $path=str_replace('\\','/',$savename);
	        $result['data'] = [
	        	'src' => '/storage/'.$path,
	        	'title' => $fileObj->getOriginalName(),
	        	];
	        // $result['filename'] = $fileObj->getOriginalName();
	        
	        // $result['url'] = '/storage/'.$path;

	    } catch (\think\exception\ValidateException $e) {
	    	$result['code'] = -1;
            $result['info'] =  $e->getMessage();
            $result['url'] = '';
	    }

	    return $result;
    }
    // 附件上传
    public function uploads(){
        //获取上传文件表单字段名
        $type = input('type','file');
        $path = input('path','images');
        $file =request()->file('file') ? request()->file('file'): request()->file('upfile');
        $file_size = $file->getSize();
        $md5 = $file->md5();
        $sha1 = $file->sha1();;
        $file_mime = $file->getMime();
        $attach =  Db::name('attach')->where('md5',$md5)->find();

        if(!$attach){
            try {
                switch ($type=='file'){
                    case 'file':
                        $validate = $this->fileValidate;
                        break;
                    case 'image':
                        $validate = $this->imageValidate;
                        break;
                    case 'video':
                        $validate = $this->videoValidate;
                        break;
                    case 'voice' :
                        $validate = $this->voiceValidate;
                        break;
                    default:
                        $validate = $this->uploadValidate;
                }
                $fileArr = [];
                foreach ($file as $key => $value) {
                    $fileArr[$key] = $value;
                }
                validate($validate)->check($fileArr);
                
                $savename = \think\facade\Filesystem::disk('public')->putFile($path, $file);
                $savename=str_replace('\\','/',$savename);
                $path = '/storage/' . $savename;
            } catch (\think\exception\ValidateException $e) {
                $path = '';
                $error = $e->getMessage();
            }
            $file_ext =  strtolower(substr($savename, strrpos($savename, '.') + 1));
            $file_name = basename($savename);
            $width = $height = 0;
            if (in_array($file_mime, ['image/gif', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/png', 'image/webp']) || in_array($file_ext, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'webp'])) {
                $imgInfo = getimagesize($file->getPathname());
                ;
                if (!$imgInfo || !isset($imgInfo[0]) || !isset($imgInfo[1])) {
                    $this->error(lang('Uploaded file is not a valid image'));
                }
                $width = isset($imgInfo[0]) ? $imgInfo[0] : $width;
                $height = isset($imgInfo[1]) ? $imgInfo[1] : $height;
            }
            if (!empty($path)) {
                $data = [
                    'admin_id'=>session('admin.id'),
                    'name'=>$file_name,
                    'path'=>$path,
                    'thumb'=>$path,
                    'url'=>$this->request->domain().$path,
                    'ext'=>$file_ext,
                    'size'=>$file_size/1024,
                    'width'=>$width,
                    'height'=>$height,
                    'md5'=>$md5,
                    'sha1'=>$sha1,
                    'mime'=>$file_mime,
                    'driver'=>'local',
                    'create_time'=>time(),
                    'create_time'=>time(),

                ];
                $attach = Db::name('attach')->insert($data);
                $result['code'] = 1;
                $result['state'] = 'SUCCESS'; //兼容百度
                $result['id'] =$attach['id'];
                $result["url"] = $path;
                $result['msg'] = lang('upload success');
                return json($result);
            } else {
                //上传失败获取错误信息
                $result['url'] = '';
                $result['msg'] = $error;
                $result['code'] = 0;
                $result['state'] = 'ERROR'; //兼容百度
                return json($result);
            }

        }else{
            $result['state'] = 'SUCCESS'; //兼容百度
            $result['code'] = 1;
            $result['id'] =$attach['id'];
            //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
            $result["url"] = $attach['path'];
            $result['msg'] = lang('upload success');
            return json($result);
        }

    }
}